package oop.ex3.filemanager;

import java.io.File;
import java.io.IOException;
import java.net.Socket;

import oop.ex3.common.Protocol;
import oop.ex3.common.SocketCommunicationSession;

public class UploadThread extends Thread{
//public class UploadThread implements Runnable{	

	private SocketCommunicationSession _session;
	private File _directoryPath;

	private String _nameOfFileToUpload;
	
	public UploadThread(Socket socket, File directoryPath) {
		try {
			_session = new SocketCommunicationSession(socket);
			_directoryPath = directoryPath;
			_nameOfFileToUpload = null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	
	@Override
	public void run() {
	String message;
		try {
			message = _session.readString();
			if(message.equals(Protocol.MSG_WANT_FILE)){
				//reading the name of the wanted file:
				String wantedFile = _session.readString();
				_nameOfFileToUpload = wantedFile;
				synchronized(this){
					this.notify();
				}
				//reading END:
				message = _session.readString();
				String[] fileNames = _directoryPath.list();
				for(String fileName : fileNames){
					if(wantedFile.equals(fileName)){
						//the file exists, send it!
						
						File fileToUpload = new File(_directoryPath.getAbsolutePath()+"\\"+wantedFile);
						
						
						_session.sendString(Protocol.MSG_FILE_DOWNLOAD_BEGINS);
						_session.writeByteArray(fileToUpload);
						_session.sendString(Protocol.MSG_END);
						_session.close();
						
						return;
					}
				}
				//if the file is not found in the uploading FM's database, a FILENOTFOUND msg is sent: 
				_session.sendString(Protocol.MSG_FILE_NOT_FOUND);
				_session.close();
			}


		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	public String getFileNameOfUploadingFile(){
		return _nameOfFileToUpload;
	}

}
